package com.example.project.projectspringcloud.utils;

import com.example.project.projectspringcloud.common.Constants;
import com.example.project.projectspringcloud.entity.UserDetails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Random;

public class WebUtil {

    public static String MYDOMAIN = Constants.MYDOMAIN;

    public static void setCookie(HttpServletResponse response, String key, String value, int days) {
        setCookie(response, key, value, days, MYDOMAIN);
    }

    /**
     * 设置Cookie值
     */
    public static void setCookie(HttpServletResponse response, String key, String value, int days, String domain) {
        if ((key != null) && (value != null)) {
            Cookie cookie = new Cookie(key, value);
            cookie.setMaxAge(days * 24 * 60 * 60);
            cookie.setPath("/");
            if (StringUtils.isNotEmpty(domain)) {
                cookie.setDomain(domain);
            }
            response.addCookie(cookie);
        }
    }

    /**
     * 获取Cookie值
     */
    public static String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        String resValue = "";
        if ((cookies != null) && (cookies.length > 0)) {
            for (Cookie cooky : cookies) {
                if ((!key.equalsIgnoreCase(cooky.getName())) || (!StringUtils.isNotEmpty(cooky.getValue()))) {
                    continue;
                }
                resValue = cooky.getValue();
            }
        }
        return resValue;
    }

    /**
     * 删除默认域名下的
     */
    public static void deleteCookie(HttpServletRequest request,
                                    HttpServletResponse response, String name) {
        deleteCookieDomain(request, response, name, MYDOMAIN);
    }

    /**
     * 删除某域下的Cookie
     */
    public static void deleteCookieDomain(HttpServletRequest request,
                                          HttpServletResponse response, String name, String domain) {
        Cookie[] cookies = request.getCookies();
        if ((cookies != null) && (cookies.length > 0)) {
            for (int i = 0; i < cookies.length; i++) {
                if (!name.equalsIgnoreCase(cookies[i].getName())) {
                    continue;
                }
                Cookie ck = new Cookie(cookies[i].getName(), null);
                ck.setPath("/");
                if (StringUtils.isNotEmpty(domain)) {
                    ck.setDomain(domain);
                }
                ck.setMaxAge(0);
                response.addCookie(ck);
                return;
            }
        }
    }


    /**
     * 获取请求IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        ipAddress = request.getHeader("x-forwarded-for");
        if ((ipAddress == null) || (ipAddress.length() == 0)
                || ("unknown".equalsIgnoreCase(ipAddress))) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if ((ipAddress == null) || (ipAddress.length() == 0)
                || ("unknown".equalsIgnoreCase(ipAddress))) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if ((ipAddress == null) || (ipAddress.length() == 0)
                || ("unknown".equalsIgnoreCase(ipAddress))) {
            ipAddress = request.getRemoteAddr();
            if ("127.0.0.1".equals(ipAddress)) {
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }

        }
        if ((ipAddress != null) && (ipAddress.length() > 15)) {
            if (ipAddress.indexOf(Constants.Punctuation.COMMA) > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }


    /**
     * 获取请求URI
     */
    public static String getServletRequestUriParms(HttpServletRequest request) {
        StringBuffer sbUrlParms = new StringBuffer(request.getRequestURI());
        sbUrlParms.append("?");
        @SuppressWarnings("unchecked")
        Enumeration<String> parNames = request.getParameterNames();
        while (parNames.hasMoreElements()) {
            String parName = parNames.nextElement().toString();
            try {
                sbUrlParms.append(parName).append("=")
                        .append(URLEncoder.encode(request.getParameter(parName), "UTF-8"))
                        .append("&");
            } catch (UnsupportedEncodingException e) {
                return "";
            }
        }
        return sbUrlParms.toString();
    }

    /**
     * 正则表达试验证密码
     */
    public static boolean isPasswordAvailable(String password) {
        String partten = "^[_0-9a-zA-Z]{6,}$";
        boolean flag = (password.matches(partten)) && (password.length() >= 6) && (password.length() <= 16);
        return flag;
    }

    /**
     * 判断ajax请求
     *
     * @return <code>true</code> 如果是 ajax 请求
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String her = request.getHeader("x-requested-with");

        return StringUtils.isNotEmpty(her);
    }

    /**
     * 去html
     */
    public static String replaceTagHTML(String src) {
        src = src.replace("javascript", "");
        String regex = "\\<(.+?)\\>";
        return StringUtils.isNotEmpty(src) ? src.replaceAll(regex, "") : "";
    }

    /**
     * 获取由0-9的随机数字拼成的符串
     */
    public static String getRandomNum(int k) {
        String randomNum = "";
        for (int i = 0; i < k; i++) {
            Random rd = new Random();
            randomNum += (int) Math.floor(rd.nextInt(9));
        }
        return randomNum;
    }

    /**
     * 判断referer
     */
    public static boolean compareReferer(String referer, String trueUrl) {
        String[] baseUrl = referer.split("/");
        String refererUrl = baseUrl[0] + "//" + baseUrl[2];
        return refererUrl.equals(trueUrl);
    }

    /**
     * 访问次数限制register：要判断是否超过限制的邮箱或手机 ip ：用户ip  registerLimit：对应的邮箱或手机验证的限制次数 ipLimit：ip注册的限制次数
     */
    /*public static boolean registerLimit(String register, String ip, int registerLimit, int ipLimit) {
        // 如果缓存中没有该用户ip就将该ip和请求次数1存入缓存1天
        if (CacheUtil.get(ip) == null) {
            //把ip和验证码请求次数放入缓存
            CacheUtil.set(ip, 0, 86400);
        }
        // 获取缓存中对应ip的请求次数
        int ipCount = (int) CacheUtil.get(ip);
        if (CacheUtil.get(register) == null) {
            // 把请求用户信息和验证码请求次数放入缓存
            CacheUtil.set(register, 0, 86400);
        }
        // 发送验证码的次数
        int registerCoun = (int) CacheUtil.get(register);
        if (ipCount >= ipLimit) {
            return false;
        }
        if (registerCoun > registerLimit) {
            return false;
        }
        // 如果缓存中有该用户ip,邮箱，且请求次数小于5，就将该ip和请求次数加1存入缓存1天
        if (ipCount <= ipLimit && registerCoun <= registerLimit) {
            ipCount++;
            registerCoun++;
            // 把ip和验证码请求次数放入缓存
            CacheUtil.set(ip, ipCount, 86400);
            // 把邮箱和验证码请求次数放入缓存
            CacheUtil.set(register, registerCoun, 86400);
            return true;
        }
        return true;
    }*/

    /**
     * get current login user
     * ==============================================================================
     *
     * @return
     */
    public static UserDetails getCurrentUser() {
        if (SecurityContextHolder.getContext().getAuthentication() != null) {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principal.equals("anonymousUser")) {
                return null;
            }
            return (UserDetails) principal;
        }
        return null;
    }

    /**
     * get localhost LAN address
     * ==============================================================================
     *
     * @return
     * @throws Exception
     */
    public static InetAddress getLocalHostLANAddress() throws Exception {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    // 排除loopback类型地址
                    if (!inetAddr.isLoopbackAddress()) {
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址，就是它了
                            return inetAddr;
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress;
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            return jdkSuppliedAddress;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}